import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import './index.css'

// 缴费项目接口
interface PaymentItem {
  id: string
  registrationNo: string
  department: string
  doctor: string
  orderTime: string
  amount: number
  selected: boolean
}

function OutpatientPayment() {
  const navigate = useNavigate()
  
  // 当前选中的标签页
  const [activeTab, setActiveTab] = useState<'pending' | 'paid'>('pending')
  
  // 缴费项目数据
  const [paymentItems, setPaymentItems] = useState<PaymentItem[]>([
    {
      id: '1',
      registrationNo: '20200101001598Z',
      department: '门诊外一科',
      doctor: '刘医师',
      orderTime: '2020-01-01 10:20:36',
      amount: 520.13,
      selected: true
    },
    {
      id: '2',
      registrationNo: '20200101001602A',
      department: '口腔科',
      doctor: '章医师',
      orderTime: '2020-01-01 13:20:36',
      amount: 120.50,
      selected: false
    }
  ])

  // 已缴费记录（从本地存储读取）
  const [paidRecords, setPaidRecords] = useState<Array<{
    outTradeNo: string
    totalAmount: string
    sendPayDate: string
    department?: string
    doctor?: string
  }>>([])

  useEffect(() => {
    try {
      const key = 'paidRecords'
      const raw = localStorage.getItem(key)
      const list: Array<{ outTradeNo: string; totalAmount: string; sendPayDate: string; department?: string; doctor?: string }> = raw ? JSON.parse(raw) : []
      setPaidRecords(Array.isArray(list) ? list : [])
    } catch {
      setPaidRecords([])
    }
  }, [activeTab])

  // 计算选中项目的总金额
  const totalAmount = paymentItems
    .filter(item => item.selected)
    .reduce((sum, item) => sum + item.amount, 0)

  // 计算选中的项目数量
  const selectedCount = paymentItems.filter(item => item.selected).length

  // 处理单个项目选择
  const handleItemSelect = (id: string) => {
    setPaymentItems(prev => 
      prev.map(item => 
        item.id === id ? { ...item, selected: !item.selected } : item
      )
    )
  }

  // 处理全选
  const handleSelectAll = () => {
    const allSelected = paymentItems.every(item => item.selected)
    setPaymentItems(prev => 
      prev.map(item => ({ ...item, selected: !allSelected }))
    )
  }

  // 处理去缴费
  const handlePayment = async () => {
    if (selectedCount === 0) {
      alert('请选择要缴费的项目')
      return
    }

    try {
      // 生成订单号（这里使用时间戳+随机数，实际项目中应该由后端生成）
      const orderNo = `order_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      console.log('正在调用支付宝支付API...')
      console.log('请求参数:', {
        orderNo: orderNo,
        totalPrice: totalAmount,
        subject: `门诊缴费 - ${selectedCount}项`
      })
      
             // 调用真实的支付宝支付API
       const response = await axios.post('http://172.27.2.110/order/alipay', {
         orderNo: orderNo,
         totalPrice: totalAmount,
         subject: `门诊缴费 - ${selectedCount}项`
       }, {
         timeout: 30000, // 增加到30秒超时
         headers: {
           'Content-Type': 'application/json',
           'Access-Control-Allow-Origin': '*'
         }
       })

      console.log('API响应:', response.data)

      if (response.data.code === 200) {
        // 显示支付信息
        alert(`订单号: ${orderNo}\n支付金额: ¥${totalAmount.toFixed(2)}\n\n即将跳转到支付宝支付页面...`)
        
        // 跳转到支付宝支付页面
        window.open(response.data.url, '_blank')

        // 支付发起后，引导到“支付结果确认”页，负责轮询并在成功后跳转到缴费详情
        navigate(`/pay-result?orderNo=${orderNo}`)
      } else {
        alert(`支付失败: ${response.data.msg}`)
      }
    } catch (error: unknown) {
      console.error('支付请求失败:', error)
      
      // 详细的错误处理
      if (error && typeof error === 'object' && 'code' in error) {
        if (error.code === 'ERR_NETWORK') {
          alert('网络连接失败，请检查网络连接或稍后重试')
        } else if (error.code === 'ECONNABORTED') {
          alert('请求超时，请稍后重试')
        } else {
          alert(`网络错误: ${error.code}`)
        }
      } else if (error && typeof error === 'object' && 'response' in error) {
        // 服务器返回了错误状态码
        const axiosError = error as { response: { status: number; data?: { msg?: string } } }
        alert(`服务器错误: ${axiosError.response.status} - ${axiosError.response.data?.msg || '未知错误'}`)
      } else if (error && typeof error === 'object' && 'request' in error) {
        // 请求已发出但没有收到响应
        alert('无法连接到支付服务器，请稍后重试')
      } else {
        // 其他错误
        const errorMessage = error instanceof Error ? error.message : '未知错误'
        alert(`支付请求失败: ${errorMessage}`)
      }
    }
  }

  return (
    <div className="outpatient-payment">
      {/* 顶部导航 */}
      <div className="header">
        <div className="header-content">
          <button className="back-button" onClick={() => navigate(-1)}>
            ‹
          </button>
          <div className="title">门诊缴费</div>
          <div className="header-actions">
            <span className="action-icon">⋯</span>
            <span className="action-icon">◎</span>
          </div>
        </div>
      </div>

      {/* 患者信息 */}
      <div className="patient-info">
        <div className="patient-details">
          <span className="patient-name">王小柯</span>
          <span className="patient-id">2015****10</span>
        </div>
        <div className="switch-patient">
          <span className="switch-icon">⇄</span>
          <span className="switch-text">切换</span>
        </div>
      </div>

      {/* 缴费状态标签 */}
      <div className="payment-tabs">
        <div 
          className={`tab ${activeTab === 'pending' ? 'active' : ''}`}
          onClick={() => setActiveTab('pending')}
        >
          待缴费
        </div>
        <div 
          className={`tab ${activeTab === 'paid' ? 'active' : ''}`}
          onClick={() => setActiveTab('paid')}
        >
          已缴费
        </div>
      </div>

      {/* 缴费项目列表 */}
      <div className="payment-list">
        {activeTab === 'pending' ? (
          paymentItems.map(item => (
            <div key={item.id} className="payment-item">
              <div className="item-content">
                <div className="item-info">
                  <div className="info-row">
                    <span className="label">登记号:</span>
                    <span className="value">{item.registrationNo}</span>
                  </div>
                  <div className="info-row">
                    <span className="label">就诊科室:</span>
                    <span className="value">{item.department}</span>
                  </div>
                  <div className="info-row">
                    <span className="label">开单医生:</span>
                    <span className="value">{item.doctor}</span>
                  </div>
                  <div className="info-row">
                    <span className="label">开单时间:</span>
                    <span className="value">{item.orderTime}</span>
                  </div>
                  <div className="info-row">
                    <span className="label">开单金额:</span>
                    <span className="amount">¥{item.amount.toFixed(2)}</span>
                  </div>
                </div>
                <div className="item-actions">
                  <button 
                    className={`checkbox ${item.selected ? 'checked' : ''}`}
                    onClick={() => handleItemSelect(item.id)}
                  >
                    {item.selected && <span className="checkmark">✓</span>}
                  </button>
                  <button className="detail-link">缴费明细 ›</button>
                </div>
              </div>
            </div>
          ))
        ) : (
          paidRecords.length === 0 ? (
            <div className="empty-state">
              <div className="empty-icon">📋</div>
              <div className="empty-text">暂无已缴费记录</div>
            </div>
          ) : (
            paidRecords.map((r) => (
              <div key={r.outTradeNo} className="payment-item">
                <div className="item-content">
                  <div className="item-info">
                    <div className="info-row">
                      <span className="label">订单号:</span>
                      <span className="value">{r.outTradeNo}</span>
                    </div>
                    <div className="info-row">
                      <span className="label">金额:</span>
                      <span className="amount">¥{Number(r.totalAmount || 0).toFixed(2)}</span>
                    </div>
                    <div className="info-row">
                      <span className="label">支付时间:</span>
                      <span className="value">{r.sendPayDate || '-'}</span>
                    </div>
                    <div className="info-row">
                      <span className="label">就诊科室:</span>
                      <span className="value">{r.department || '-'}</span>
                    </div>
                    <div className="info-row">
                      <span className="label">开单医生:</span>
                      <span className="value">{r.doctor || '-'}</span>
                    </div>
                  </div>
                  <div className="item-actions">
                    <button className="detail-link" onClick={() => navigate(`/payment-success?orderNo=${r.outTradeNo}`)}>查看详情 ›</button>
                  </div>
                </div>
              </div>
            ))
          )
        )}
      </div>

      {/* 底部操作栏 */}
      {activeTab === 'pending' && (
        <div className="bottom-bar">
          <div className="select-all">
            <button 
              className={`checkbox ${selectedCount === paymentItems.length ? 'checked' : ''}`}
              onClick={handleSelectAll}
            >
              {selectedCount === paymentItems.length && <span className="checkmark">✓</span>}
            </button>
            <span className="select-text">全选 (已选 {selectedCount} 张)</span>
          </div>
          <div className="payment-summary">
            <div className="total-amount">合计: ¥{totalAmount.toFixed(2)}</div>
            <button 
              className="payment-button"
              onClick={handlePayment}
              disabled={selectedCount === 0}
            >
              去缴费
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

export default OutpatientPayment

